package com.gcmm.controller;

import com.gcmm.utils.TableUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
@Slf4j
@Controller
@RequestMapping("/database/table")
public class DatabaseController {
    @GetMapping
    public String forward(  Model model) {
        model.addAttribute("ip",TableUtils.getIp());
        model.addAttribute("port",TableUtils.getPort());
        model.addAttribute("username",TableUtils.getUsername());
        model.addAttribute("password",TableUtils.getPassword());
        model.addAttribute("schema",TableUtils.getSchema());

        return "databaseTableForm";
    }
        @PostMapping
        public String makeTable(String ip,String username,String password,String port,String schema, MultipartFile classFile, Model model) {
     log.info("ip:{},username:{},password:{},port:{},schema:{}",ip,username,password,port,schema);
            TableUtils.setIp(ip);
            TableUtils.setSchema(schema);
            TableUtils.setUsername(username);
            TableUtils.setPassword(password);
            TableUtils.setPort(port);
            String sql=null;
            try {
                sql = TableUtils.createTableByFile(classFile);
log.info("sql:{}",sql);
            } catch (Exception e)  {
                log.info("error to get the sql ：{}",e.getMessage());
                throw new RuntimeException(e);
            }
            model.addAttribute("ip",TableUtils.getIp());
            model.addAttribute("port",TableUtils.getPort());
            model.addAttribute("username",TableUtils.getUsername());
            model.addAttribute("password",TableUtils.getPassword());
            model.addAttribute("schema",TableUtils.getSchema());
            model.addAttribute("sql",sql);
            return "databaseTableForm";
        }

}
